/* James McTaggart (jcm28) Informatics
Multimedia Communications Technology - 17th May 2007
In making this submission I declare that my work contains no examples
of misconduct, such as plagiarism, collusion, or fabrication of results.
*/

package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Vector;

public class Server {


	private Vector<Connection> connections = new Vector<Connection>();
	
	public Server(int delay, int period, int serverPort, String radioAddress,int radioPort) {

		byte[] inData = new byte[60];
		byte[] outData = new byte[60];
		try{
			DatagramSocket serverSocket = new DatagramSocket(serverPort);
			RadioServer radioServer = new RadioServer(delay,period);
			radioServer.start();
			DatagramPacket inPacket = new DatagramPacket(inData,inData.length);
			String in;
			int clientPort; 
			InetAddress clientAddress; 
			
			BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
			UserInputThread inputThread = new UserInputThread(userIn,serverSocket,connections);
			inputThread.start();
			System.out.println("Server started. To bleep samples please enter 'BLEEP' or 'B'. To stop samples being bleeped enter the same again. The system can be exited by entering 'EXIT'");
			while(true){
				serverSocket.receive(inPacket);
				clientPort = inPacket.getPort();
				clientAddress = inPacket.getAddress();
				
				Connection c = new Connection(clientPort,clientAddress);
				if(!connections.contains(c))connections.add(c);
				in = new String(inPacket.getData());
				int n = getMessageID(in);
				switch(n){
				case -1:break;
				case 101:
					serverSocket.send(ServerProtocol.get201(clientPort,clientAddress,delay,period,radioAddress,radioPort));
					break;
				case 102:
					connections.remove(c);
					break;
				default:break;
				}
				Thread.yield();
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private int getMessageID(String message) {
		try {
			int id = Integer.parseInt(message.substring(0, 3));
			if (id != 101 && id != 102) {
				return -1;
			}
			return id;
		} catch (NumberFormatException e) {
			return -1;
		}
	}
 
	public static void main(String[] args) {
		if(args.length==0){
			Server server = new Server(5000,1000, 7777, "localhost", 7778);
		}
		//int delay, int period, int serverPort, String radioAddress,int radioPort
		else{
			int delay = Integer.parseInt(args[0]);
			int period = Integer.parseInt(args[1]);
			int serverPort = Integer.parseInt(args[2]);
			int radioPort = Integer.parseInt(args[4]);
			Server server = new Server(delay,period,serverPort,args[3],radioPort);
		}
	}
}
